/**********************************************************************************
  Snes9x - Portable Super Nintendo Entertainment System (TM) emulator.

  (c) Copyright 1996 - 2002  Gary Henderson (gary.henderson@ntlworld.com),
                             Jerremy Koot (jkoot@snes9x.com)

  (c) Copyright 2002 - 2004  Matthew Kendora

  (c) Copyright 2002 - 2005  Peter Bortas (peter@bortas.org)

  (c) Copyright 2004 - 2005  Joel Yliluoma (http://iki.fi/bisqwit/)

  (c) Copyright 2001 - 2006  John Weidman (jweidman@slip.net)

  (c) Copyright 2002 - 2006  funkyass (funkyass@spam.shaw.ca),
                             Kris Bleakley (codeviolation@hotmail.com)

  (c) Copyright 2002 - 2007  Brad Jorsch (anomie@users.sourceforge.net),
                             Nach (n-a-c-h@users.sourceforge.net),
                             zones (kasumitokoduck@yahoo.com)

  (c) Copyright 2006 - 2007  nitsuja


  BS-X C emulator code
  (c) Copyright 2005 - 2006  Dreamer Nom,
                             zones

  C4 x86 assembler and some C emulation code
  (c) Copyright 2000 - 2003  _Demo_ (_demo_@zsnes.com),
                             Nach,
                             zsKnight (zsknight@zsnes.com)

  C4 C++ code
  (c) Copyright 2003 - 2006  Brad Jorsch,
                             Nach

  DSP-1 emulator code
  (c) Copyright 1998 - 2006  _Demo_,
                             Andreas Naive (andreasnaive@gmail.com)
                             Gary Henderson,
                             Ivar (ivar@snes9x.com),
                             John Weidman,
                             Kris Bleakley,
                             Matthew Kendora,
                             Nach,
                             neviksti (neviksti@hotmail.com)

  DSP-2 emulator code
  (c) Copyright 2003         John Weidman,
                             Kris Bleakley,
                             Lord Nightmare (lord_nightmare@users.sourceforge.net),
                             Matthew Kendora,
                             neviksti


  DSP-3 emulator code
  (c) Copyright 2003 - 2006  John Weidman,
                             Kris Bleakley,
                             Lancer,
                             z80 gaiden

  DSP-4 emulator code
  (c) Copyright 2004 - 2006  Dreamer Nom,
                             John Weidman,
                             Kris Bleakley,
                             Nach,
                             z80 gaiden

  OBC1 emulator code
  (c) Copyright 2001 - 2004  zsKnight,
                             pagefault (pagefault@zsnes.com),
                             Kris Bleakley,
                             Ported from x86 assembler to C by sanmaiwashi

  SPC7110 and RTC C++ emulator code
  (c) Copyright 2002         Matthew Kendora with research by
                             zsKnight,
                             John Weidman,
                             Dark Force

  S-DD1 C emulator code
  (c) Copyright 2003         Brad Jorsch with research by
                             Andreas Naive,
                             John Weidman

  S-RTC C emulator code
  (c) Copyright 2001-2006    byuu,
                             John Weidman

  ST010 C++ emulator code
  (c) Copyright 2003         Feather,
                             John Weidman,
                             Kris Bleakley,
                             Matthew Kendora

  Super FX x86 assembler emulator code
  (c) Copyright 1998 - 2003  _Demo_,
                             pagefault,
                             zsKnight,

  Super FX C emulator code
  (c) Copyright 1997 - 1999  Ivar,
                             Gary Henderson,
                             John Weidman

  Sound DSP emulator code is derived from SNEeSe and OpenSPC:
  (c) Copyright 1998 - 2003  Brad Martin
  (c) Copyright 1998 - 2006  Charles Bilyue'

  SH assembler code partly based on x86 assembler code
  (c) Copyright 2002 - 2004  Marcus Comstedt (marcus@mc.pp.se)

  2xSaI filter
  (c) Copyright 1999 - 2001  Derek Liauw Kie Fa

  HQ2x, HQ3x, HQ4x filters
  (c) Copyright 2003         Maxim Stepin (maxim@hiend3d.com)

  Win32 GUI code
  (c) Copyright 2003 - 2006  blip,
                             funkyass,
                             Matthew Kendora,
                             Nach,
                             nitsuja

  Mac OS GUI code
  (c) Copyright 1998 - 2001  John Stiles
  (c) Copyright 2001 - 2007  zones


  Specific ports contains the works of other authors. See headers in
  individual files.


  Snes9x homepage: http://www.snes9x.com

  Permission to use, copy, modify and/or distribute Snes9x in both binary
  and source form, for non-commercial purposes, is hereby granted without
  fee, providing that this license information and copyright notice appear
  with all copies and any derived work.

  This software is provided 'as-is', without any express or implied
  warranty. In no event shall the authors be held liable for any damages
  arising from the use of this software or it's derivatives.

  Snes9x is freeware for PERSONAL USE only. Commercial users should
  seek permission of the copyright holders first. Commercial use includes,
  but is not limited to, charging money for Snes9x or software derived from
  Snes9x, including Snes9x or derivatives in commercial game bundles, and/or
  using Snes9x as a promotion for your commercial product.

  The copyright holders request that bug fixes and improvements to the code
  should be forwarded to them so everyone can benefit from the modifications
  in future versions.

  Super NES and Super Nintendo Entertainment System are trademarks of
  Nintendo Co., Limited and its subsidiary companies.
**********************************************************************************/

/**********************************************************************************
  Snes9x GTK Port
  
  (c) Copyright 2007 - 2008  Brandon Wright (bearoso@gmail.com)
**********************************************************************************/

#include <stdlib.h>
#include <gdk/gdkkeysyms.h>

#include "gtk_preferences.h"
#include "gtk_config.h"
#include "gtk_s9xcore.h"
#include "gtk_control.h"
#include "gtk_sound.h"
#include "gtk_display.h"

static void 
binding_to_string (Binding bin, char *str)
{
    char buf[256];
    str[0] = '\0';
    char *c;
        
    if (bin & BINDING_KEY)
    {
        char *keyval_name = NULL;
        unsigned int keyval = gdk_keyval_to_lower (bin & BINDING_KEY_MASK);
        keyval_name = gdk_keyval_name (keyval);
        
        if (keyval_name == NULL)
        {
            sprintf (buf, "Unknown");
        }
        
        else 
        {
            strncpy (buf, 
                     keyval_name, 
                     256);
        }
        
        while ((c = strstr (buf, "_")))
        {
            *c = ' '; 
        }
        
        sprintf (str, "Keyboard %s%s%s%s",
                 bin & BINDING_SHIFT ? "Shift+" : "",
                 bin & BINDING_CTRL  ? "Ctrl+"  : "",
                 bin & BINDING_ALT   ? "Alt+"   : "",
                 buf);
    }
    
    else if (bin & BINDING_JOY)
    {
        if ((bin & BINDING_KEY_MASK) >= 512)
            sprintf (buf, 
                     "Axis #%d %s %d%%",
                     JOY_AXIS_UNMASK (bin),
                     JOY_DIRECTION_UNMASK (bin) == AXIS_POS ? "+" : "-",
                     THRESHOLD_UNMASK (bin));
        else
            sprintf (buf, "Button %d", bin & BINDING_KEY_MASK);
        
        sprintf (str, "Joystick %d %s", JOY_DEVICE_UNMASK(bin), buf);
    }
    
    else
    {
        sprintf (str, "Undefined");
    }
    
    return;
}

gboolean
snes9x_preferences_open (GtkWidget *widget,
                         gpointer data)
{
    Snes9xPreferences *preferences;
    Snes9xConfig *config = (Snes9xConfig *) data;
    
    preferences = new Snes9xPreferences ((Snes9xConfig *) data);
    
#ifdef USE_JOYSTICK
    config->set_joystick_mode (JOY_MODE_GLOBAL);
#endif
    
    preferences->show ();
    
#ifdef USE_JOYSTICK
    config->set_joystick_mode (JOY_MODE_INDIVIDUAL);
#endif
    
    config->reconfigure ();
    top_level->update_accels ();
    
    delete preferences;
    
    return TRUE;
}


static void
untoggle_by_glade_if_not (GladeXML *glade, 
                          GtkToggleButton *button, 
                          const char *name)
{
    GtkToggleButton *toggle = GTK_TOGGLE_BUTTON (
                                  glade_xml_get_widget (glade, name));
    
    if (toggle == button || !toggle)
        return;
    
    gtk_toggle_button_set_active (toggle, FALSE);
    
    return;
}

static void
event_sram_folder_browse (GtkButton *widget, gpointer data)
{
    ((Snes9xPreferences *) data)->browse_folder_dialog ();

    return;
}

#ifdef USE_JOYSTICK
static void
event_calibrate (GtkButton *widget, gpointer data)
{
    ((Snes9xPreferences *) data)->calibration_dialog ();

    return;
}
#endif

static void
event_control_toggle (GtkToggleButton *widget, gpointer data)
{
    Snes9xPreferences *window = (Snes9xPreferences *) data;
    static unsigned char toggle_lock = 0;
    
    if (toggle_lock)
        return;
    
    window->last_toggled = widget;
    
    toggle_lock = 1;
    
    for (int i = 0; b_links[i].button_name; i++)
    {
        untoggle_by_glade_if_not (window->glade, 
                                  widget, 
                                  b_links[i].button_name);
    }
    
    toggle_lock = 0;
    
    return;
}

static gboolean 
event_key_press (GtkWidget *widget, GdkEventKey *event, gpointer user_data)
{
    Binding key_binding = 0;
    GtkToggleButton *button = NULL;
    Snes9xPreferences *window = (Snes9xPreferences *) user_data;
        
    if (!(button = GTK_TOGGLE_BUTTON (window->any_toggled ()))) 
    {
        return FALSE; /* Don't keep key for ourselves */    
    }
    
    /* Don't allow modifiers that we track to be bound */ 
    if (event->keyval == GDK_Control_L ||
        event->keyval == GDK_Control_R ||
        event->keyval == GDK_Shift_L   ||
        event->keyval == GDK_Shift_R   ||
        event->keyval == GDK_Alt_L     ||
        event->keyval == GDK_Alt_R)
    {
        return FALSE;
    }
    
    key_binding = event->keyval & BINDING_KEY_MASK;
    
    key_binding |= BINDING_KEY;
    
    /* Generate key binding */
    if (event->state & GDK_SHIFT_MASK)
        key_binding |= BINDING_SHIFT;
    
    if (event->state & GDK_CONTROL_MASK)
        key_binding |= BINDING_CTRL;
    
    if (event->state & GDK_MOD1_MASK)
        key_binding |= BINDING_ALT;
    
    /* Allows ESC key to clear the key binding */
    if (event->keyval == GDK_Escape)
    {
        key_binding = 0;
    }
    
    window->store_binding ((char *) gtk_widget_get_name (GTK_WIDGET (button)), 
                           key_binding);
    
    window->untoggle_all ();
    
    return TRUE;
}


static void
event_control_combo_changed (GtkComboBox *widget, gpointer user_data)
{
    Snes9xPreferences *window = (Snes9xPreferences *) user_data;
    
    window->bindings_to_dialog (gtk_combo_box_get_active (widget));
    
    return;
}

static void 
event_switch_page (GtkNotebook *notebook,
                   GtkNotebookPage *page,
                   guint page_num,
                   gpointer data)
{
    Snes9xPreferences *window = (Snes9xPreferences *) data;
        
    window->untoggle_all ();
    
    return;
}

#ifdef USE_JOYSTICK

void
Snes9xPreferences::calibration_dialog (void)
{
    GtkWidget *dialog;
    
    config->joystick_register_centers ();
    config->set_joystick_mode (JOY_MODE_CALIBRATE);
    dialog = gtk_message_dialog_new (NULL,
                                     (GtkDialogFlags) 0,
                                     GTK_MESSAGE_INFO,
                                     GTK_BUTTONS_OK,
                                     "Rotate all axes to their maximum values, then press OK");

    gtk_dialog_run (GTK_DIALOG (dialog));
    
    config->set_joystick_mode (JOY_MODE_GLOBAL);
    
    gtk_widget_destroy (dialog);
    
    return;
}

static gboolean
poll_joystick (gpointer data)
{
    Snes9xPreferences *window = (Snes9xPreferences *) data;
    GtkToggleButton *button;
    JoyEvent event;
    Binding key_binding;
    int i;
        
    for (i = 0; window->config->joystick[i]; i++)
    {
        while (window->config->joystick[i]->get_event (&event))
        {
            if (event.state == JOY_PRESSED)
            {
                if ((button = GTK_TOGGLE_BUTTON (window->any_toggled ()))) 
                {       
                    key_binding = BINDING_JOY;
                    key_binding |= JOY_DEVICE_MASK (i + 1);
                    key_binding |= event.parameter;
                    if (event.parameter >= 512)
                        key_binding |= THRESHOLD_MASK (
                                       window->config->joystick_threshold);
                    
                    window->store_binding ((char *) gtk_widget_get_name 
                                               (GTK_WIDGET (button)), 
                                           key_binding);
                                        
                    window->untoggle_all ();
                    window->config->flush_joysticks (); 
                    return TRUE;
                }
                
            }
        }
    }  
    
    return TRUE;
}
#endif

void
Snes9xPreferences::set_button_label (const char *name, const char *label)
{
    GtkWidget *widget;
    
    widget = glade_xml_get_widget (glade, name);
    
    gtk_button_set_label (GTK_BUTTON (widget), label);
    
    return;
}

void
Snes9xPreferences::bindings_to_dialog (int joypad)
{
    char name[256];
    Binding *bindings = (Binding *) &pad[joypad];
    
    set_combo ("control_combo", joypad);
    
    for (int i = 0; i < NUM_JOYPAD_LINKS; i++)
    {
        binding_to_string (bindings[i], name);
        set_button_label (b_links[i].button_name, name);
    }
    
    for (int i = NUM_JOYPAD_LINKS; b_links[i].button_name; i++)
    {
        binding_to_string (shortcut[i - NUM_JOYPAD_LINKS], name);
        set_button_label (b_links[i].button_name, name);
    }

    return;
}

unsigned char
Snes9xPreferences::get_check (const char *name)
{
    GtkToggleButton *widget;
    
    widget = GTK_TOGGLE_BUTTON (glade_xml_get_widget (glade, name));
    
    if (gtk_toggle_button_get_active (widget))
        return 1;
    return 0;   
}

unsigned int
Snes9xPreferences::get_entry (const char *name)
{
    GtkEntry *widget;
    unsigned int value;
    
    widget = GTK_ENTRY (glade_xml_get_widget (glade, name));
    
    value = atoi (gtk_entry_get_text (widget));
    
    return value;
}

const char *
Snes9xPreferences::get_entry_text (const char *name)
{
    GtkEntry *widget;
    
    widget = GTK_ENTRY (glade_xml_get_widget (glade, name));
    
    return gtk_entry_get_text (widget);
}

unsigned char
Snes9xPreferences::get_combo (const char *name)
{
    GtkComboBox *widget;
    
    widget = GTK_COMBO_BOX (glade_xml_get_widget (glade, name));
    
    return gtk_combo_box_get_active (widget);   
}

void
Snes9xPreferences::set_check (const char *name, unsigned char value)
{
    GtkToggleButton *widget;
    
    widget = GTK_TOGGLE_BUTTON (glade_xml_get_widget (glade, name));
        
    gtk_toggle_button_set_active (widget, value);
    
    return;
}

void
Snes9xPreferences::set_entry (const char *name, unsigned int value)
{
    GtkEntry *widget;
    char text[80];
    
    widget = GTK_ENTRY (glade_xml_get_widget (glade, name));
        
    snprintf (text, 80, "%u", value);
    gtk_entry_set_text (widget, text);
    
    return;
}

void
Snes9xPreferences::set_entry_text (const char *name, const char *text)
{
    GtkEntry *widget;
    
    widget = GTK_ENTRY (glade_xml_get_widget (glade, name));
        
    gtk_entry_set_text (widget, text);
    
    return;
}

void
Snes9xPreferences::set_combo (const char *name, unsigned char value)
{
    GtkComboBox *widget;
    
    widget = GTK_COMBO_BOX (glade_xml_get_widget (glade, name));
        
    gtk_combo_box_set_active (widget, value);
    
    return;
}

void
Snes9xPreferences::set_spin (const char *name, unsigned int value)
{
    GtkSpinButton *spin;
    
    spin = GTK_SPIN_BUTTON (glade_xml_get_widget (glade, name));
    
    gtk_spin_button_set_value (spin, (double) value);
    
    return;
}

unsigned int
Snes9xPreferences::get_spin (const char *name)
{
    GtkSpinButton *spin;
    
    spin = GTK_SPIN_BUTTON (glade_xml_get_widget (glade, name));
    
    return (unsigned int) gtk_spin_button_get_value (spin);
}

void
Snes9xPreferences::store_binding (const char *string, Binding binding)
{
    int current_joypad = get_combo ("control_combo");
    Binding *pad_bindings = (Binding *) (&pad[current_joypad]);
    
    for (int i = 0; i < NUM_JOYPAD_LINKS; i++)
    {
        if (!strcmp (b_links[i].button_name, string))
        {
            pad_bindings[i] = binding;
        }
        else
        {
            if (pad_bindings[i] == binding ||
                (pad_bindings[i] & ~BINDING_THRESHOLD_MASK) ==
                (binding & ~BINDING_THRESHOLD_MASK))
                pad_bindings[i] = 0;
        }
    }
    
    for (int i = NUM_JOYPAD_LINKS; b_links[i].button_name; i++)
    {
        if (!strcmp (b_links[i].button_name, string))
        {
            shortcut[i - NUM_JOYPAD_LINKS] = binding;
        }
        else
        {
            if (shortcut[i - NUM_JOYPAD_LINKS] == binding ||
                (shortcut[i - NUM_JOYPAD_LINKS] & ~BINDING_THRESHOLD_MASK) ==
                (binding & ~BINDING_THRESHOLD_MASK))
                shortcut[i - NUM_JOYPAD_LINKS] = 0;
        }
    }
    
    bindings_to_dialog (get_combo ("control_combo"));
    
    return;
}

GtkWidget *
Snes9xPreferences::any_toggled (void)
{
    for (int i = 0; b_links[i].button_name; i++)
    {
        if (get_check (b_links[i].button_name))
        {
            return glade_xml_get_widget (glade, b_links[i].button_name);
        }
    }
    
    return NULL;
}

void
Snes9xPreferences::untoggle_all (void)
{
    int i;
    
    for (i = 0; b_links[i].button_name; i++)
    {
        gtk_toggle_button_set_active (
            GTK_TOGGLE_BUTTON (
                glade_xml_get_widget (glade, b_links[i].button_name)),
                FALSE);
    }
}

Snes9xPreferences::Snes9xPreferences (Snes9xConfig *config)
{
    const char *version_string = "Snes9x Version " VERSION "\n"
                                 "(c) Copyright Respective Authors\n\n"
                                 "GTK Port Version " SNES9X_GTK_VERSION "\n"
                                 "\nOpenGL support: "
#ifdef USE_OPENGL
                                 "enabled"
#else
                                 "disabled"
#endif
                                 
                                 "\nJoystick support: "
#ifdef USE_JOYSTICK
                                 "enabled"
#else
                                 "disabled"
#endif
                                 "\n\n" SNES9X_GTK_AUTHORS;
    
    glade = glade_xml_new_from_buffer (_binary_snes9x_glade_start,
                                       _binary_snes9x_glade_end -
                                           _binary_snes9x_glade_start,
                                       "preferences_window", 
                                       NULL);
    
    window = glade_xml_get_widget (glade, "preferences_window");
    
    gtk_label_set_label (GTK_LABEL (
                             glade_xml_get_widget (glade,
                                                   "version_string_label")),
                         version_string);
    
    last_toggled = NULL;
    
    size_group[0] = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);
    
    gtk_size_group_add_widget (size_group[0],
        GTK_WIDGET (glade_xml_get_widget (glade, "resolution_combo")));
    
    gtk_size_group_add_widget (size_group[0],
            GTK_WIDGET (glade_xml_get_widget (glade, "scale_method_combo")));
    
    size_group[1] = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);
        
    gtk_size_group_add_widget (size_group[1],
        GTK_WIDGET (glade_xml_get_widget (glade, "change_display_resolution")));
        
    gtk_size_group_add_widget (size_group[1],
        GTK_WIDGET (glade_xml_get_widget (glade, "scale_method_label")));   
    
    gtk_widget_realize (window);
    
    glade_xml_signal_connect_data (glade,
                                   "control_toggle",
                                   G_CALLBACK (event_control_toggle),
                                   (gpointer) this); 
    
    glade_xml_signal_connect_data (glade,
                                   "on_key_press",
                                   G_CALLBACK (event_key_press),
                                   (gpointer) this);
    
    glade_xml_signal_connect_data (glade,
                                   "control_combo_changed",
                                   G_CALLBACK (event_control_combo_changed),
                                   (gpointer) this);
    
    glade_xml_signal_connect_data (glade,
                                   "change_current_page",
                                   G_CALLBACK (event_switch_page),
                                   (gpointer) this);
    
    glade_xml_signal_connect_data (glade,
                                   "sram_folder_browse",
                                   G_CALLBACK (event_sram_folder_browse),
                                   (gpointer) this);
    
#ifdef USE_JOYSTICK
    glade_xml_signal_connect_data (glade,
                                   "calibrate",
                                   G_CALLBACK (event_calibrate),
                                   (gpointer) this);
#endif

        
    this->config = config;
        
    return;
}

Snes9xPreferences::~Snes9xPreferences (void)
{
    g_object_unref (glade);
    g_object_unref (size_group[0]);
    g_object_unref (size_group[1]);
    
    return;
}

void
Snes9xPreferences::move_settings_to_dialog (void)
{
    set_check ("full_screen_on_open",       config->full_screen_on_open);
    set_check ("show_frame_rate",           Settings.DisplayFrameRate);
    set_check ("transparency",              Settings.Transparency);
    set_check ("change_display_resolution", config->change_display_resolution);
    set_check ("scale_to_fit",              config->scale_to_fit);
    set_check ("overscan",                  config->overscan);
    set_check ("multithreading",            config->multithreading);
    set_check ("maintain_aspect_ratio",     config->maintain_aspect_ratio);
    set_check ("rom_folder_radio",          config->data_location==DIR_ROM);
    set_check ("config_folder_radio",       config->data_location==DIR_CONFIG);
    set_check ("custom_folder_radio",       config->data_location==DIR_CUSTOM);
    set_entry_text ("custom_folder_entry",  config->custom_sram_directory);
    set_combo ("resolution_combo",          config->xrr_index); 
    set_combo ("scale_method_combo",        config->scale_method);
    set_entry ("save_sram_after_sec",       Settings.AutoSaveDelay);
    
    set_combo ("frameskip_combo",
               Settings.SkipFrames == AUTO_FRAMERATE ?
                   0 : Settings.SkipFrames + 1);
    set_check ("speedhacks_check",          Settings.ShutdownMaster);
    set_check ("hdma_check",                !(Settings.DisableHDMA));
    
    set_check ("sound_emulation_check",     Settings.APUEnabled);
    set_check ("16bit_check",               Settings.SixteenBitSound);
    set_check ("stereo_check",              Settings.Stereo);
    set_check ("reverse_stereo_check",      Settings.ReverseStereo);
    set_check ("gaussian_interpolation_check", Settings.InterpolatedSound);
    set_check ("vehr_check",              Settings.SoundEnvelopeHeightReading);
    set_check ("echo_check",                !(Settings.DisableSoundEcho));
    set_check ("master_volume_check",       !(Settings.DisableMasterVolume));
    
    set_combo ("playback_combo",            7 - Settings.SoundPlaybackRate);
    set_combo ("sample_combo",              Settings.AltSampleDecode == 0 ?
                                            0 : Settings.AltSampleDecode == 1 ?
                                                    1 : 2);
#ifdef USE_OPENGL
    set_check ("use_opengl",                config->use_opengl);
    set_check ("bilinear_filter",           config->bilinear_filter);
    set_check ("sync_to_vblank",            config->sync_to_vblank);
    set_check ("use_pbos",                  config->use_pbos);
    set_combo ("pixel_format",              config->pbo_format == GL_RGB ? 0 : 
                                            config->pbo_format == GL_BGRA ? 1 : 0);
#else   
    gtk_widget_set_sensitive (glade_xml_get_widget (glade, "opengl_frame"),
                              FALSE);
/*    gtk_widget_set_sensitive (glade_xml_get_widget (glade, "bilinear_filter"),
                              FALSE);
    gtk_widget_set_sensitive (glade_xml_get_widget (glade, "sync_to_vblank"),
                              FALSE); */
#endif
    
#ifdef USE_JOYSTICK
    set_spin ("joystick_threshold",         config->joystick_threshold);
#else
    gtk_widget_set_sensitive (
        glade_xml_get_widget (glade, "joystick_box"), FALSE);
#endif
    
    /* Control bindings */
    memcpy (pad, config->pad, (sizeof (JoypadBinding)) * NUM_JOYPADS);
    memcpy (shortcut, config->shortcut, (sizeof (Binding)) * NUM_EMU_LINKS);
    bindings_to_dialog (0);
    
    return;
}

void
Snes9xPreferences::get_settings_from_dialog (void)
{
    int sound_needs_restart = 0;
    int gfx_needs_restart   = 0;
    
    if ((Settings.APUEnabled        != get_check ("sound_emulation_check")) ||
        (Settings.Stereo            != get_check ("stereo_check"))          ||
        (Settings.SoundPlaybackRate != 
            (uint32) (7 - (get_combo ("playback_combo"))))                  ||
        (Settings.SixteenBitSound   != get_check ("16bit_check"))           ||
        (Settings.InterpolatedSound != 
            get_check ("gaussian_interpolation_check"))                     ||
        (Settings.SoundEnvelopeHeightReading !=
            get_check ("vehr_check"))                                       ||
        (Settings.ReverseStereo     != get_check ("reverse_stereo_check"))  ||
        (Settings.DisableMasterVolume != 
            !(get_check ("master_volume_check")))                           ||
        (Settings.DisableSoundEcho  != !(get_check ("echo_check")))         ||
        (Settings.AltSampleDecode != (get_combo ("sample_combo") == 2 ?
                                         3 :get_combo ("sample_combo"))))
    {
        sound_needs_restart = 1;
    }
#ifdef USE_OPENGL
    if (config->use_opengl != get_check ("use_opengl") ||
        (config->use_opengl && 
                config->sync_to_vblank != get_check ("sync_to_vblank")))
        gfx_needs_restart = 1;
#endif
    
    config->full_screen_on_open       = get_check ("full_screen_on_open");
    Settings.DisplayFrameRate         = get_check ("show_frame_rate");
    Settings.Transparency             = get_check ("transparency");
    config->change_display_resolution = get_check ("change_display_resolution");
    config->scale_to_fit              = get_check ("scale_to_fit");
    config->overscan                  = get_check ("overscan");
    config->maintain_aspect_ratio     = get_check ("maintain_aspect_ratio");
    
    if (config->multithreading != get_check ("multithreading"))
        gfx_needs_restart = 1;
    
    config->multithreading            = get_check ("multithreading");
#ifdef USE_OPENGL
    config->use_opengl                = get_check ("use_opengl");
    config->bilinear_filter           = get_check ("bilinear_filter");
    config->sync_to_vblank            = get_check ("sync_to_vblank");
    
    if (config->use_pbos != get_check ("use_pbos"))
        gfx_needs_restart = 1;
    
    config->use_pbos                  = get_check ("use_pbos");
    
    if (get_combo ("pixel_format") == 0)
        config->pbo_format = GL_RGB;
    else
        config->pbo_format = GL_BGRA;
    
#endif
    config->data_location             = get_check ("rom_folder_radio") ? 
                                            DIR_ROM : config->data_location;
    config->data_location             = get_check ("config_folder_radio") ? 
                                            DIR_CONFIG : config->data_location;
    config->data_location             = get_check ("custom_folder_radio") ? 
                                            DIR_CUSTOM : config->data_location;
    strncpy (config->custom_sram_directory, 
             get_entry_text ("custom_folder_entry"),
             PATH_MAX);
                    
    config->xrr_index                 = get_combo ("resolution_combo");
    config->scale_method              = get_combo ("scale_method_combo");
    Settings.AutoSaveDelay            = get_entry ("save_sram_after_sec");
    
#ifdef USE_JOYSTICK
    config->joystick_threshold        = get_spin ("joystick_threshold");
#endif
     
    Settings.SkipFrames = get_combo ("frameskip_combo");
    if (Settings.SkipFrames == 0)
    {
        Settings.SkipFrames = AUTO_FRAMERATE;
    }
    else
    {
        Settings.SkipFrames--;
    }
    
    Settings.DisableHDMA = !(get_check ("hdma_check"));
    Settings.ShutdownMaster = get_check ("speedhacks_check");
    
    Settings.APUEnabled = Settings.NextAPUEnabled =
        get_check ("sound_emulation_check");
    Settings.SixteenBitSound = get_check ("16bit_check");
    Settings.Stereo = get_check ("stereo_check");
    Settings.ReverseStereo = get_check ("reverse_stereo_check");
    Settings.InterpolatedSound = get_check ("gaussian_interpolation_check");
    Settings.SoundEnvelopeHeightReading = get_check ("vehr_check");
    Settings.DisableSoundEcho = !(get_check ("echo_check"));
    Settings.DisableMasterVolume = !(get_check ("master_volume_check"));
    Settings.SoundPlaybackRate = 7 - (get_combo ("playback_combo"));
    Settings.SoundBufferSize = buffer_sizes[Settings.SoundPlaybackRate];
    Settings.AltSampleDecode = get_combo ("sample_combo");
    if (Settings.AltSampleDecode == 2)
        Settings.AltSampleDecode = 3;
    
    memcpy (config->pad, pad, (sizeof (JoypadBinding)) * NUM_JOYPADS);
    memcpy (config->shortcut, shortcut, (sizeof (Binding)) * NUM_EMU_LINKS);
    
    if (sound_needs_restart)
    {
        S9xInitSound (Settings.SoundPlaybackRate,
                      Settings.Stereo,
                      Settings.SoundBufferSize);
    }
    
    if (gfx_needs_restart)
    {
        top_level->last_width = top_level->last_height = SIZE_FLAG_NO_DRAWING;
        S9xReinitDisplay ();
        S9xDeinitUpdate (top_level->last_width, top_level->last_height);
    }
    else
    {
        S9xDisplayRefresh (top_level->last_width, top_level->last_height);
        S9xDeinitUpdate (top_level->last_width, top_level->last_height);
    }
    
    return;
}

void
Snes9xPreferences::browse_folder_dialog (void)
{
    GtkWidget *dialog;
    char *filename;
    gint result;
    
    top_level->pause_from_focus_change ();
    
    dialog = gtk_file_chooser_dialog_new ("Select Folder",
                                          GTK_WINDOW (this->window),
                                          GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
                                          GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                          GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
                                          NULL);
    
    gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog),
                                         S9xGetDirectory (HOME_DIR));
    
    result = gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_hide_all (dialog);
    
    if (result == GTK_RESPONSE_ACCEPT)   
    {
        filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));

        gtk_entry_set_text (GTK_ENTRY (
                                glade_xml_get_widget (glade, 
                                                      "custom_folder_entry")),
                            filename);
        
        g_free (filename);
    }
    
    else
    {
    }
    
    gtk_widget_destroy (dialog);
    
    top_level->unpause_from_focus_change ();

    return;
}

void
Snes9xPreferences::show (void)
{
    gint result;
    GtkWidget *combo;
    char size_string[256];
    int close_dialog;
#ifdef USE_JOYSTICK
    guint source_id;
#endif        
    
    combo = glade_xml_get_widget (glade, "resolution_combo");
    
    for (int i = 0; i < config->xrr_num_sizes; i++)
    {
        snprintf (size_string, 
                  256, 
                  "%dx%d",
                  config->xrr_sizes[i].width,
                  config->xrr_sizes[i].height);
        
        gtk_combo_box_append_text (GTK_COMBO_BOX (combo), size_string);
    }
    
    move_settings_to_dialog (); 
    top_level->pause_from_focus_change ();
#ifdef USE_JOYSTICK
    source_id = g_timeout_add (100, poll_joystick, (gpointer) this);
#endif
    
    for (close_dialog = 0; !close_dialog; )
    {
        result = gtk_dialog_run (GTK_DIALOG (window));
        
        switch (result)
        {
            case GTK_RESPONSE_OK:
                get_settings_from_dialog ();
                config->save_config_file ();
                close_dialog = 1;
                break;
            
            case GTK_RESPONSE_APPLY:
                get_settings_from_dialog ();
                config->save_config_file ();
                break;
                
            default:
                close_dialog = 1;
                break;
        }
    }
    
#ifdef USE_JOYSTICK
    g_source_remove (source_id);
#endif
    
    gtk_widget_destroy (window);
        
    top_level->unpause_from_focus_change ();
    
    return;
}
